class Solution {
public:
    int latestTimeCatchTheBus(vector<int>& buses, vector<int>& passengers, int capacity)
    {
        ranges::sort(buses);
        ranges::sort(passengers);
        int cnt = 0;
        int i = 0, j = 0;
        for (auto& a : buses)
        {
            cnt = capacity;
            while (cnt > 0 && j < passengers.size() && passengers[j] <= a)
                cnt--, j++;
        }
        j--;
        int ans = cnt > 0 ? buses.back() : passengers[j];
        while (j >= 0 && ans == passengers[j]) j--, ans--;

        return ans;

    }

};